<?php
/**
 * ===============================================
 * 版权所有 2019-2050 青岛铁锤科技有限公司，并保留所有权利。
 * 网站地址: http://www.huaxianling.com
 * ===============================================
 * Author: Happy dong
 * Created Time: 2019-06-25 10:19
 * Modified Time: 2019-06-25 10:19
 * Version: 2.0
 */

namespace App\Modules\Employee\Services;


use App\Exceptions\AllValidatorException;
use App\Exceptions\NotFoundException;
use App\Lib\Facades\FLAuth;
use App\Lib\Utilities;
use App\Modules\Employee\Criterias\WxGetStoreDynamicListCriteria;
use App\Modules\Employee\Criterias\WxGetVideoDynamicListCrireria;
use App\Modules\Employee\Repositories\DynamicLikeRepository;
use App\Modules\Employee\Repositories\DynamicRepository;
use App\Modules\Employee\Repositories\DynamicResourceRepository;
use Flower\Core\Repository\Eloquent\BaseService;
use Flower\Core\Repository\Exceptions\ValidatorException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\MessageBag;

class DynamicService extends BaseService
{
    private $dynamicRepository;
    private $dynamicLikeRepository;
	private $dynamicResourceRepository;
	public function __construct(DynamicRepository $dynamicRepository, DynamicLikeRepository $dynamicLikeRepository, DynamicResourceRepository $dynamicResourceRepository)
	{
        $this->dynamicRepository = $dynamicRepository;
        $this->dynamicLikeRepository = $dynamicLikeRepository;
        $this->dynamicResourceRepository = $dynamicResourceRepository;
	}

	/**
	 * 获取动态列表
	 * @param $userId
	 * @param $pageSize
	 * @return mixed
	 * @throws \Flower\Core\Repository\Exceptions\RepositoryException
	 */
	public function getDynamicList($userId,$store_id,$pageSize){
		$list =  $this->dynamicRepository->getList($userId,$store_id,$pageSize);
		foreach ($list->items() as $v){
			foreach ($v->resource as $j){
				$j->imgOrVideoUrl;
			}
		}
		return $list;
//		$res = array_map(function($v){
//			$imgList = Utilities::arrayColumnGroup($v['resource'],'picture');
//			$imgList = array_filter($imgList,function($s){return !empty($s); });
//			$videoList = Utilities::arrayColumnGroup($v['resource'], 'video');
//			$videoList =array_filter($videoList,function($e){return !empty($e); });
//			return  [
//				'id' => $v['id'],
//				'user_id' => $v['user_id'],
//				'content' => $v['content'],
//				'imgList' => $imgList,
//				'videoList' => $videoList
//			];
//		},$res);
//		return $res;
	}

	/**
	 * 新增动态 视频或者图片或者文字动态
	 * @param $userId
	 * @param $detail
	 * @param $image
	 * @param $video
	 * @return mixed
	 */
	public function addNewDynamic($userId,$store_id,$detail,$image,$video){
		$resourceId = empty($video) ? json_decode($image,true) : $video;
		DB::beginTransaction();
		$dynamic = $this->dynamicRepository->addDynamic($userId,$store_id,$detail);
		$flag = true;
		// 插入动态资源
        if(!empty($resourceId)){
            $res = $this->dynamicResourceRepository->insertData($dynamic->id,$userId, $resourceId);
            $flag = empty($res) ?false : true;
        }
        $flag = !empty($dynamic) && $flag;
        $flag ? DB::commit() : DB::rollBack();
		return $flag;
	}

	/**
	 * 编辑动态
	 * @param $userId
	 * @param $detail
	 * @param $image
	 * @param $video
	 * @param $dynamicId
	 * @return mixed
	 * @throws NotFoundException
	 */
	public function editDynamic($userId,$detail,$image,$video,$dynamicId){
		$dynamic = $this->dynamicRepository->isExisted($dynamicId);
		if($dynamic->user_id != $userId){
			throw new NotFoundException(['msg'=>'您对此条动态无操作权限！']);
		}
		$resourceId = empty($video) ? json_decode($image,true) : $video;
		DB::beginTransaction();
		$dynamic = $this->dynamicRepository->edit($dynamicId,$detail);

		if(!empty($resourceId)){
			$this->dynamicResourceRepository->deleteByDynamicId($dynamicId);
			// 动态资源
			$res = $this->dynamicResourceRepository->insertData($dynamic->id,$userId, $resourceId);
		}
		$res = empty($resourceId) ? true : $res;
		$result = !empty($dynamic) && $res ;
		$result	? DB::commit() : DB::rollBack();
		return $result;
	}

	/**
	 * 删除动态
	 * @param $userId
	 * @param $dynamicId
	 * @return int
	 * @throws NotFoundException
	 */
	public function deleteDynamic($userId,$dynamicId){
		$dynamic = $this->dynamicRepository->isExisted($dynamicId);
		if($dynamic->user_id != $userId){
			throw new NotFoundException(['msg'=>'对不起，您对该动态无操作权限']);
		}
		return $this->dynamicRepository->delete($dynamicId);
	}

	/*
	 * 获取视频动态
	 */
	public function getVideoDynamicList($requestData)
    {

        $pageSize = isset($requestData['pageSize'])?$requestData['pageSize']:10;

        $list = $this->dynamicRepository
                        ->pushCriteria(new WxGetVideoDynamicListCrireria($requestData))
                        ->paginate($pageSize,['*'],'paginate');

        $list = Utilities::dealPage($list);
        return $list;
    }

    /*
     * 动态点赞
     */
    public function dynamicLike($requestData)
    {
        $rule = [
            'dynamic_id' => '缺少动态id',
            'operation' => '缺少操作值'
        ];

        Utilities::checkRequestDataKeyExist($requestData,$rule);

        $flAuth = new FLAuth();
        $operation = $requestData['operation'];
        $member_id = $flAuth->id();
        $dynamic_id = $requestData['dynamic_id'];

        if($operation==1){//点赞
            $this->dynamicLikeRepository->firstOrCreate(['member_id'=>$member_id,'dynamic_id'=>$dynamic_id]);
        }else{//取消赞
            $like = $this->dynamicLikeRepository->findByField(['member_id'=>$member_id,'dynamic_id'=>$dynamic_id]);
            if($like->count()!=0){
                $this->dynamicLikeRepository->deleteWhere(['member_id'=>$member_id,'dynamic_id'=>$dynamic_id]);
            }
        }

    }

    /*
     * 获取某店下所有理发师发的动态
     */
    public function getStoreDynamicList($store_id,$pageSize)
    {
        $list = $this->dynamicRepository->pushCriteria(new WxGetStoreDynamicListCriteria($store_id))->paginate($pageSize,['*']);

        $list = Utilities::dealPage($list);
        return $list;
    }

}
